package com.zhixiang.wbl.visitor.fragement;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.Toast;

import com.daimajia.slider.library.Animations.DescriptionAnimation;
import com.daimajia.slider.library.SliderLayout;
import com.daimajia.slider.library.SliderTypes.BaseSliderView;
import com.daimajia.slider.library.SliderTypes.TextSliderView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.snappydb.DB;
import com.snappydb.DBFactory;
import com.snappydb.SnappydbException;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.xys.libzxing.zxing.activity.CaptureActivity;
import com.zhixiang.wbl.visitor.Constant.Constant;
import com.zhixiang.wbl.visitor.Constant.DBConstant;
import com.zhixiang.wbl.visitor.Helper.BaseCallback;
import com.zhixiang.wbl.visitor.Helper.OkHttpHelper;
import com.zhixiang.wbl.visitor.Helper.SpotsCallBack;
import com.zhixiang.wbl.visitor.R;
import com.zhixiang.wbl.visitor.Utils.URLUtil;
import com.zhixiang.wbl.visitor.Utils.VisitorUtil;
import com.zhixiang.wbl.visitor.adapter.HomeAdapter;
import com.zhixiang.wbl.visitor.decoration.DividerItemDecoration;
import com.zhixiang.wbl.visitor.model.Banner;
import com.zhixiang.wbl.visitor.model.RootBanner;
import com.zhixiang.wbl.visitor.model.home.HomeDate;
import com.zhixiang.wbl.visitor.model.home.RootHome;
import com.zhixiang.wbl.visitor.model.location.LocationModel;
import com.zhixiang.wbl.visitor.model.location.RootLocation;
import com.zhixiang.wbl.visitor.model.login.Visitor;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by dongzhixiang on 16/5/17.
 */
public class HomeFragment extends BaseFragment implements View.OnClickListener
{
    private static final String TAG = "HomeFragment";
    @ViewInject(R.id.slider)
    SliderLayout mSliderLayout;//广告动态展示栏
    @ViewInject(R.id.id_recyclerview)
    RecyclerView mRecyclerView;
    @ViewInject(R.id.id_button_scan)
    ImageButton scanButton;
    private OkHttpHelper httpHelper = OkHttpHelper.getInstance();
    private List<Banner> mBanner = new ArrayList<>();
    private static final int BannerType = 1;
    private static final int HomeType = 2;
    private HomeDate mHomeDate;
    private HomeAdapter mAdapter;
    @Override
    public View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view=  inflater.inflate(R.layout.fragment_home, container, false);
        return  view;
    }

    @Override
    public void init()
    {
      //从网络获取Banner数据
      getBannerDateFromServer();
        //从服务器端获取主页其他数据
      getHomePageDateFromServer();
      scanButton.setOnClickListener(this);
    }
    /*
    * 从网络获取Banner数据
    * */
    public void getBannerDateFromServer()
    {
        httpHelper.get(Constant.BANNER_URL, new SpotsCallBack<RootBanner>(getContext(),"正在获取数据")
        {
            @Override
            public void onSuccess(Response response, RootBanner rootBanner)
            {
                if (200 == rootBanner.getCode())
                {
                    mBanner.clear();
                    Banner[] banners = rootBanner.getData();
                    mBanner.addAll(Arrays.asList(banners));
                    try {
                        DB snapyDB = DBFactory.open(getContext());
                        snapyDB.put(DBConstant.HomeFragment_BANNER_KEY,banners);
                    } catch (SnappydbException e)
                    {
                        e.printStackTrace();
                    }
                   //发送更新Banner命令
                   Message msg = new Message();
                   msg.what = BannerType;
                   mHandler.sendMessage(msg);
                }
                else
                {
                    readBannerCache();
                }
            }

            @Override
            public void onError(Response response, int code, Exception e) {
               readBannerCache();
            }
        });
    }
    /*
    * 从缓存中读取Banner数据
    * */
    public void readBannerCache()
    {
        try {
            DB snapyDB = DBFactory.open(getContext());
            Banner[] banners=  snapyDB.getObjectArray(DBConstant.HomeFragment_BANNER_KEY,Banner.class);
            mBanner = Arrays.asList(banners);
            if (mBanner!=null)
            {
                //发送更新Banner命令
                Message msg = new Message();
                msg.what = BannerType;
                mHandler.sendMessage(msg);
            }
        } catch (SnappydbException e) {
            e.printStackTrace();
        }
    }
    /*
    * 初始化Banner
    * */
    private void initSlider()
    {
        if(mBanner !=null)
        {
            for (Banner banner : mBanner)
            {
                TextSliderView textSliderView = new TextSliderView(this.getActivity());
                String url = banner.getImageurl();
                textSliderView.image(url);
                textSliderView.description(banner.getTitle());
                textSliderView.setScaleType(BaseSliderView.ScaleType.Fit);
                mSliderLayout.addSlider(textSliderView);
            }
        }
        mSliderLayout.setPresetIndicator(SliderLayout.PresetIndicators.Center_Bottom);
        mSliderLayout.setCustomAnimation(new DescriptionAnimation());
        mSliderLayout.setPresetTransformer(SliderLayout.Transformer.RotateUp);
        mSliderLayout.setDuration(3000);
    }
    /*
    * 通知更新首页界面
    * */
    private void notifyUpdateHomePage(LocationModel loc)
    {
        Message msg = new Message();
        msg.obj = loc;
        msg.what =  0x123;
        handler.sendMessage(msg);
    }
    /*
    * 从服务器端获取其他网络数据
    * */
    private void getHomePageDateFromServer()
   {
        //先通过缓存读取当前用户的位置信息
        final LocationModel location = VisitorUtil.getLocation(getContext());
       if (location!=null)
       {
           notifyUpdateHomePage(location);
       }
       else //通过服务器获取当前的用户的位置信息
       {

       }
        Visitor mVisitor = VisitorUtil.getCurrentVisitor(getContext());
        if (mVisitor!=null)
        {
            //获取游客的ID
          int userId =  mVisitor.getId();
         //根据游客ID获取当前游客所在的位置
            Map<String,String> locationMap = new HashMap<>();
            locationMap.put("userId",userId+"");
            String locationUrl = URLUtil.getURL( Constant.LOCATION_GET_URL ,locationMap);
            httpHelper.get(locationUrl, new BaseCallback<RootLocation>()
            {
                @Override
                public void onBeforeRequest(Request request) {

                }

                @Override
                public void onFailure(Request request, Exception e) {

                }

                @Override
                public void onResponse(Response response) {

                }

                @Override
                public void onSuccess(Response response, RootLocation rootLocation)
                {
                    //先更新用户信息
                   VisitorUtil.cacheLocation(getContext(),rootLocation.getData());
                  //  位置获取成功后，就可以更新，页面信息
                   notifyUpdateHomePage(rootLocation.getData());
                }

                @Override
                public void onError(Response response, int code, Exception e) {
                   //失败则获取缓存的信息
                    LocationModel loc = VisitorUtil.getLocation(getContext());
                    if (loc!=null)
                    {
                        notifyUpdateHomePage(loc);
                    }
                }
            });
        }


    }
    public void updateHomePage(LocationModel location)
    {
        double latitude = location.getLatitude();
        double longtitude =location.getLongtitude();

        Map<String,String> map = new HashMap<>();
        // double latitude = 30.509763;
        map.put("latitude",latitude+"");
        //  double longtitude = 114.413385;
        map.put("longtitude",longtitude+"");
        String url = URLUtil.getURL(Constant.HOME_PAGE_URL,map);
        //http://115.156.196.64/api/index.php/Home/Spot/getSpots?latitude=114.413469&longtitude=114.413469
        httpHelper.get(url, new SpotsCallBack<RootHome>(getContext(),"正在努力加载")
        {
            @Override
            public void onSuccess(Response response, RootHome rootHome)
            {
                if (200 == rootHome.getCode())
                {
                    mHomeDate = rootHome.getData();
                    //成功获取数据先保存一下
                    try {
                        DB snappydb = DBFactory.open(getContext());
                        snappydb.put(DBConstant.HomeFragment_SPOTDATE_KEY,mHomeDate);
                    } catch (SnappydbException e) {
                        e.printStackTrace();
                    }
                    Message message = new Message();
                    message.what = HomeType;
                    mHandler.sendMessage(message);
                }

                else
                {
                    readCacheHomeDateFromDB();
                }
            }
            @Override
            public void onError(Response response, int code, Exception e)
            {
               readCacheHomeDateFromDB();
            //    Log.e(TAG, "onError: "+code);
            }
        });
    }
    /*
    * 从缓存中读取首页数据
    * */
    private void readCacheHomeDateFromDB()
    {
        try {
            DB snappydb = DBFactory.open(getContext());
            mHomeDate =  snappydb.get(DBConstant.HomeFragment_SPOTDATE_KEY,HomeDate.class);
            //如果缓存数据存在
            if (mHomeDate!=null)
            {
                Log.e(TAG, "onError: 读取缓存数据："+mHomeDate );
                Message message = new Message();
                message.what = HomeType;
                mHandler.sendMessage(message);
            }
        } catch (SnappydbException e1) {
            e1.printStackTrace();
        }
    }
    /**
     * 定义一个Hanfler对象主要用于页面数据请求后的操作
     *
     */
    Handler handler = new Handler()
    {
        @Override
        public void handleMessage(Message msg)
        {
            if (msg.what == 0x123)//成功获取了页面信息
            {
                LocationModel location = (LocationModel) msg.obj;
                updateHomePage(location);
            }
        }
    };
    /*
    * 初始化RecyclerView
    * */
   private void initRecyclerView()
   {
       if (mHomeDate!=null)
       {
           mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
           mAdapter = new HomeAdapter(mHomeDate, getContext());
           mRecyclerView.setAdapter(mAdapter);
           mRecyclerView.addItemDecoration(new DividerItemDecoration(getActivity(),
                   DividerItemDecoration.VERTICAL_LIST));
       }
   }
    Handler mHandler = new Handler()
    {
        @Override
        public void handleMessage(Message msg)
        {
            super.handleMessage(msg);
            if (msg.what == BannerType)
            {
                initSlider();
            }
            else if (msg.what == HomeType)
            {
                 initRecyclerView();
            }
        }
    };
    private static final int SCAN_QR_CODE =1;
    /*
    * 二维码按钮点击事件
    * */
    private void scanQR()
    {
        Intent intent = new Intent(getActivity(),CaptureActivity.class);
        startActivityForResult(intent,SCAN_QR_CODE);
    }

    @Override
    public void onClick(View v)
    {
       if (v.getId()== R.id.id_button_scan)
       {
           scanQR();
       }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK)
        {
            if (requestCode == SCAN_QR_CODE)
            {
               Bundle bundle = data.getExtras();
               String result = bundle.getString("result");
               Toast.makeText(getContext(),"结果："+result,Toast.LENGTH_SHORT).show();
            }
        }
    }
}
